package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    //根据用户名查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //调用userService，根据用户名查询用户
        User user = userService.fingByUsername(username);

        if(user == null){
            //没有查到用户信息
            return null;//禁止用户访问
        }

        //GrantedAuthority是授予角色和权限的接口
        List<GrantedAuthority> list = new ArrayList<>();

        //获取角色
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));//SimpleGrantedAuthority是GrantedAuthority的实现类

            //获取权限
            Set<Permission> permissions = role.getPermissions();

            for (Permission permission : permissions) {

                //授予权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        /*
        参数： username
                    数据库中查询到的password
                    list 用户所拥有的权限和角色集合
         spring-security框架中保存有前端登录所输入的密码，我们传入数据库中的密码，框架会自动进行比对
         */
        org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);

        return userDetails;
    }
}
